using System;
using System.Web.UI;
using System.Web;

namespace Web.Ajax.Controls
{
	/// <summary>
	/// Represents a Html Popup. 
	/// 
	/// The Aspx Markup will look something like this:
	///	<c:Popup ID="Popup" runat="server">
	///		<Title>
	///			<Left>Left Title Content</Left>
	///			<Middle>Middle Title Content</Middle> 
	///			<Right>Right Title Content</Right>
	///		</Title>
	///		<!--Place Popup Content Here-->
	///	</c:Popup>
	/// 
	/// The rendered Html will looked something like this:
	///	<iframe id=\"Modal_Background\" class=\"PopupBackground\" onload=\"this.contentWindow.document.body.style.backgroundColor='gray';\"></iframe>
	///	<div id="PopupID_Content" class="PopupPanel">
	///		<table cellpadding="0" cellspacing="0" id="PopupID_Table">
	///			<tr>
	///				<td class="PopupTitleLeft" style="width:33%;">Left Title Content</td>	
	///				<td class="PopupTitleMiddle" style="width:33%;">Middle Title Content</td>	
	///				<td class="PopupTitleRight" style="width:33%;">
	///					<table cellpadding="0" cellspacing="0" style="width:100%;">
	///						<tr>
	///							<td>Right Title Content</td>
	///							<td style="padding-left:3px;"><img alt="Close" src="/AdminTool/Images/Close.png" title="Close" onclick="PopupID.Hide();" /></td>
	///						</tr>
	///					</table>
	///				</td>	
	///			</tr>
	///			<tr>
	///				<td colspan="3" id="PopupID_InnerContent">Content
	///				</td>
	///			</tr>
	///		</table>
	///	</div>	
	///	<script type="text/javascript">var PopupID=new Popup('PopupID');</script>
	/// 
	/// The Javascript required for this control is currently located in Utilities.js.
	/// </summary>
	[ToolboxData(@"
<{0}:Popup runat=""server"">
	<Title>
		<Left>Title</Left>
		<Middle></Middle>
		<Right></Right>
	</Title>
	<!--Place Popup Content Here-->
</{0}:Popup>")]
	[ControlBuilderAttribute(typeof(PopupBuilder))]
	[ParseChildren(false)]
    public class Popup : AjaxControl
	{
		#region Constructor
		/// <summary>
		/// Constructor
		/// </summary>
		public Popup()
		{
			EnableViewState = false;
			CssClass = "PopupPanel";
		} 
		#endregion


        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Web.Ajax.Page p = Page as Web.Ajax.Page;
            if (p != null)
            {
                p.RegisterStyleSheet(Resources.StyleSheets.Popup);
                p.RegisterJavascriptFile(Resources.Javascript.Popup);
                p.RegisterJavascriptFile(Resources.Javascript.DragDrop);
            }
		}

		#region Dragable
		/// <summary>
		/// Indicates whether the popup is dragable by clicking on the title and moving the mouse.
		/// </summary>
		public bool Dragable = true;
		#endregion

		#region Resizable
		private bool resizable = false;
		public bool Resizable
		{
			get { return resizable; }
			set { resizable = value; }
		} 
		#endregion

		#region Width
		public string width = "";
		public new string Width
		{
			get
			{
				return width;
			}
			set
			{
				width = value;
			}
		} 
		#endregion

		#region Height
		public string height = "";
		public new string Height
		{
			get
			{
				return height;
			}
			set
			{
				height = value;
			}
		} 
		#endregion

		#region Maximized
		public bool maximized = false;
		public  bool Maximized
		{
			get
			{
				return maximized;
			}
			set
			{
				maximized = value;
			}
		}
		#endregion
		
		#region Modal
		/// <summary>
		/// Renders a transparent background while the popup is displayed if true. Otherwise the user can interact with the background.
		/// </summary>
		private bool modal = true; 
		public bool Modal
		{
			get { return modal;}
			set { modal = value; }
		}
		#endregion

		#region RenderTitle
		/// <summary>
		/// Render the PopupTitle Control if it is not null.
		/// </summary>
		/// <param name="writer">A HtmlTextWriter</param>
		protected void RenderTitle(HtmlTextWriter writer)
		{
			if (PopupTitle != null)
			{
				if (PopupTitle.TitleRight != null)
					PopupTitle.TitleRight.Type = Type;
				PopupTitle.Render(writer, JavascriptId);
			}
		} 
		#endregion

		#region PopupTitle
		private PopupTitle popupTitle;
		public PopupTitle PopupTitle
		{
			get
			{
				if (popupTitle == null)
				{
					for (int i = 0; i < Controls.Count; i++)
					{
						if (Controls[i] is PopupTitle)
							popupTitle = (Controls[i] as PopupTitle);
					}
				}
				return popupTitle;
			}
		}

		

		#endregion

		public bool DontRenderModalIFrame { get; set; }

		public string Type;

		public int LeftOffset = 0;
		public int TopOffset = 0;

		
		public static void RenderBackgroundIFrame(HttpContext Context, HtmlTextWriter writer)
		{
			if (Context.Items["ModalBackground"] == null)	//Only write the Background html once on the page
			{

				writer.Write("<iframe id=\"Modal_Background\" src=\"" + Web.Ajax.Page.StaticResolveUrl("~/resource.axd?Null") + "\" class=\"PopupBackground\" onload=\"this.contentWindow.document.body.style.backgroundColor='#333';\" style=\"width:0px;height:0px;position:absolute;\"></iframe>");
				Context.Items["ModalBackground"] = "written";
			}
		}

		#region RenderBeginTag
		/// <summary>
		/// Overridden RenderBeginTag().
		/// </summary>
		/// <param name="writer"></param>
		public override void RenderBeginTag(HtmlTextWriter writer)
		{
			if (!DontRenderModalIFrame)//&&Context.Items["ModalBackground"] == null)	//Only write the Background html once on the page
			{
				RenderBackgroundIFrame(Context, writer);
				//writer.Write("<iframe id=\"Modal_Background\" src=\"resource.axd?Null\" class=\"PopupBackground\" onload=\"this.contentWindow.document.body.style.backgroundColor='#333';\" style=\"width:0px;height:0px;position:absolute;\"></iframe>");
				//Context.Items["ModalBackground"] = "written";
			}
			if (!Modal)
				CssClass += " NotModal";
			writer.Write("<div id=\"" + JavascriptId + "_Content\" class=\"" + CssClass + " "+Type+ "\" >");

			if (!Modal && Browser == Browser.IE6)
				writer.Write("<iframe id=\"" + JavascriptId + "Frame\" src=\"resource.axd?Null\" class=\"PopupIE6Background\" frameborder=\"0\"></iframe>");

			writer.Write("<table cellpadding=\"0\" cellspacing=\"0\" id=\"" + JavascriptId + "_Table\"  ");
			if(!string.IsNullOrEmpty(Width))
				writer.Write("width=\""+Width+"\" ");
			if (!string.IsNullOrEmpty(Height))
				writer.Write("height=\"" + Height + "\" ");
			writer.Write(">");
			RenderTitle(writer);
			int Colspan = 1;
			if (PopupTitle != null && PopupTitle.PartCount > 1)
				Colspan = PopupTitle.PartCount;
            writer.Write("<tr><td class=\"PopupLeft\"></td><td colspan=\"" + Colspan.ToString() + "\" id=\"" + JavascriptId + "_InnerContent\" class=\"PopupContent\">");
        } 
		#endregion

		#region RenderFooter
		/// <summary>
		/// 
		/// </summary>
		/// <param name="writer"></param>
		public void RenderFooter(HtmlTextWriter writer)
		{
			if (!Resizable)
				return;
			writer.Write("<tr style=\"height:11px;position:relative;top:-11;vertical-align:bottom\">");
			writer.Write("<td colspan=\"3\" style=\"text-align:right;\">");

            string url = Resources.ImageUrl(Resources.Images.Resize);
            writer.Write("<img src=\"" + url + "\" style=\"cursor:se-resize\" id=\"" + JavascriptId + "_Resize\"/>");
			writer.Write("</td></tr>");
		} 
		#endregion
		
		#region RenderEndTag
		/// <summary>
		/// Overridden RenderEndTag().
		/// </summary>
		/// <param name="writer"></param>
		public override void RenderEndTag(HtmlTextWriter writer)
		{
            int Colspan = 1;
            if (PopupTitle != null && PopupTitle.PartCount > 1)
                Colspan = PopupTitle.PartCount;

			writer.Write("</td>");
            writer.Write("<td class=\"PopupRight\"></td></tr>");
            writer.Write("<tr><td class=\"PopupBottomLeft\"></td><td class=\"PopupBottom\" colspan=\"" + Colspan.ToString() + "\"></td><td class=\"PopupBottomRight\"></td></tr>");

			RenderFooter(writer);
			writer.Write("</table>");
			writer.Write("</div>");
			writer.WriteLine(@"<script type=""text/javascript"">");
			writer.WriteLine("var " + JavascriptId + "=new Popup('" + JavascriptId + "');");
			if (Modal == false)
				writer.WriteLine(JavascriptId + ".Modal=false;");
			if (Maximized)
				writer.WriteLine(JavascriptId + ".Maximised=true;");
			if (Dragable)
				writer.WriteLine("DragDrop.MakeDragable('"+JavascriptId+"_Title','"+JavascriptId+"_Content')");
			if (Resizable)
				writer.WriteLine("Resize.MakeResizable('" + JavascriptId + "_Resize','" + JavascriptId + "_Table')");
            RenderJavascriptId(writer);

			RenderProperty(writer, "LeftOffset", LeftOffset);
			RenderProperty(writer, "TopOffset", TopOffset);

			writer.WriteLine("</script>");
		} 
		#endregion
	}

	#region PopupBuilder
	/// <summary>
	/// The Control Builder for the Popup Control.
	/// </summary>
	internal class PopupBuilder : ControlBuilder
	{
		public override Type GetChildControlType(string tagName, System.Collections.IDictionary attribs)
		{
			if (tagName.ToLower() == "title")
				return typeof(PopupTitle);
			return base.GetChildControlType(tagName,attribs);
		}
	}
	#endregion

	//Call Form.Controls.AddAt(0, new Web.Ajax.Controls.PopupBackground());
	//in the Page_Load if you are having issue with background not appearing 
	//(usually happens when tab on page that has (non Main) Popup)
	public class PopupBackground : WebControl
	{
		protected override void Render(HtmlTextWriter writer)
		{
			Popup.RenderBackgroundIFrame(Context, writer);
		}
	}
}
